<template>
  <div class="custom-line-renderer">
    <el-button
        style="position: absolute;top: 50px;right: 50px;z-index: 1000"
        type="primary"
        @click="importImage"
    >上传</el-button>

    <!-- 上传弹窗 -->
    <el-dialog :visible.sync="upload" width="25%">
      <div style="margin-bottom: 15px">
        <el-upload
            class="upload-demo"
            drag
            :show-file-list="false"
            :headers="headers"
            :action="`${$apiHost}/common/fileImgUrl`"
            :on-success="onSuccess"
            :on-error="onError"
            :before-upload="onBefore"
            multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传excel文件，且不超过500kb</div>
        </el-upload>
      </div>
      <!-- 进度条 -->
      <el-progress v-if="loading" :percentage="progress" :status="progressStatus"></el-progress>
    </el-dialog>

    <!-- Canvas 弹窗 -->
    <el-dialog :visible.sync="canvasDialog" width="100%" top="0" @opened="initCanvas">
      <canvas ref="canvas" id="drawing-canvas" class="drawing-canvas"></canvas>
    </el-dialog>
  </div>
</template>

<script>
import html2canvas from "html2canvas";

export default {
  name: "drawCad",
  data() {
    return {
      canvas: null,
      ctx: null,
      upload: false,
      canvasDialog: false,
      linesData: [],
      loading: false,       // 控制进度条显示
      progress: 0,          // 进度百分比
      progressStatus:"",   // success / exception
    };
  },
  computed: {
    headers() {
      const token = this.token || this.$quinn.getStorage("token");
      return { token };
    },
  },
  methods: {
    importImage() {
      this.upload = true;
    },
    async getData(val) {
      try {
        this.progress = 50; // 上传成功 → 解析数据中
        const linesData = await this.$api.orderGetDXFPoints({ dxfFilePath: val });
        this.linesData = linesData;
        this.progress = 80; // 数据获取完成 → 等待绘制

        // 打开弹窗，等弹窗渲染后再绘制
        this.canvasDialog = true;

        // 等待下一个 tick，确保 canvas 渲染
        this.$nextTick(() => {
          setTimeout(() => {
            this.drawLines();
            this.progress = 100;
            this.progressStatus = "success";
            setTimeout(() => {
              this.loading = false; // 1秒后隐藏进度条
              this.progress = 0;
            }, 1000);
          }, 500);
        });
      } catch (e) {
        this.progressStatus = "exception";
        this.loading = false;
      }
    },
    initCanvas() {
      this.canvas = this.$refs.canvas;
      this.ctx = this.canvas.getContext("2d");
      this.resizeCanvas();
      window.addEventListener("resize", this.handleResize);
    },
    handleResize() {
      this.resizeCanvas();
      this.drawLines();
    },
    resizeCanvas() {
      const { width, height } = this.canvas.getBoundingClientRect();
      this.canvas.width = width || 1000;
      this.canvas.height = height || 800;
    },
    drawLines() {
      this.clearCanvas();
      if (!this.linesData || this.linesData.length === 0) return;
      this.linesData.forEach((line) => {
        if (line.type === "LINE" && Array.isArray(line.points)) {
          line.points.forEach((seg) => {
            this.ctx.beginPath();
            this.ctx.moveTo(seg.startX, seg.startY);
            this.ctx.lineTo(seg.endX, seg.endY);
            this.ctx.strokeStyle = line.color || "#000";
            this.ctx.lineWidth = line.width || 1;
            this.ctx.stroke();
          });
        } else if (line.type === "TEXT") {
          this.ctx.font = "12px Arial";
          this.ctx.fillStyle = "black";
          this.ctx.fillText(line.text, line.pointsX, line.pointsY);
        }
      });
    },
    clearCanvas() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    onSuccess(res) {
      if (res.code != 200) {
        this.$message(res.msg);
      } else {
        this.$message({ message: "导入成功！", type: "success" });
        if (res.result[0]) {
          this.loading = true;
          this.progress = 20; // 上传成功 → 开始处理
          this.getData(res.result[0]);
        }
      }
    },
    onError() {
      this.loading = false;
      this.progressStatus = "exception";
      this.$message("导入失败");
    },
    onBefore() {
      this.loading = true;
      this.progress = 10; // 开始上传
    },
  },
};
</script>

<style scoped>
.drawing-canvas {
  border-radius: 4px;
  width: 100%;
  height: 100%;
}
</style>
